// 使用 React Context 提供 store
import { createContext, useContext, useEffect } from "react";
import { RootStore, createRootStore } from "./RootStore";
import type { StoreContextValue, StoreProviderProps } from "./index.d";

const StoreContext = createContext<StoreContextValue | null>(null);
export const StoreProvider: React.FC<StoreProviderProps>=({children}: StoreProviderProps) => {
      // 调用 createRootStore 创建 store 实例
  const rootStore = createRootStore();

  useEffect(() => {
    rootStore.initialize();
    return () => rootStore.dispose();
  }, [rootStore]);

  const value: StoreContextValue = {
    rootStore
  };

  return (
    <StoreContext.Provider value={value}>{children}</StoreContext.Provider>
  );
}

export const useStore = (): RootStore => {
  const context = useContext(StoreContext);
  if (!context) {
    throw new Error("useStore must be used within a StoreProvider");
  }
  return context.rootStore;
};
